const app = getApp()
Page({
  data: {
    data_list: [],
    sets: null,
    isLoading: false,
    firstRefresh: false,
    page: 0,
    toolbar: "",
    catid:1,
    type: '全部',
    toolTop: 0,//初始化获取高度用于onpagescroll
  }, refresh(back) {
    wx.cloud.callFunction({name:'function',data:{type:"getPost",page:0,where:{type:this.data.type}}}).then(res=>{
      this.setData({ page: 0, firstRefresh: true })
      this.setData({ sets: res.result.user.data })
      if (back) { back(res) }
    })
  }, onLoad() {
    wx.setNavigationBarTitle({ title:"首页广场" })
    var that = this;
    that.setData({
      data_list: [
        { catid: '1', catname: '全部' },
        { catid: '2', catname: '日常动态' },
        { catid: '3', catname: '表白墙' },
        { catid: '4', catname: '失物招领' },
        { catid: '5', catname: '学术交流' },
        { catid: '6', catname: '校园淘宝' },
        { catid: '7', catname: '美食美景' }]
    })
  },onShow(){
    this.refresh()
  },onPageScroll(a) {
    if (a.scrollTop > this.data.toolTop) {
      this.setData({ toolbar: "position:fixed" })
    } else {
      this.setData({ toolbar: "" })
    }
    this.setData({ toolbar: this.data.toolbar })
  }, caseType: function (e) {
    var that = this;
    that.setData({ catid: e.currentTarget.dataset.catid })
    this.setData({ type: this.data.data_list[e.currentTarget.dataset.catid - 1].catname })
    this.refresh()
  }, onReady() {
    var that = this
    var query = wx.createSelectorQuery()
    query.select('#toolbar').boundingClientRect(function (res) {
      that.setData({ toolTop: res.top })
    }).exec();
  }, onPullDownRefresh: function () {
    this.refresh(function (res) {
      wx.stopPullDownRefresh()
    })
  }, onReachBottom() {
    if ((!this.data.isLoading) && this.data.firstRefresh) {
      this.setData({ isLoading: true, page: this.data.page + 1 })
      wx.cloud.callFunction({ name: 'function', data: { type: "getPost", page: this.data.page, where: { type: this.data.type } } }).then(res => {
        if (res.result.user.data.length < 10) { this.setData({ page: this.data.page }) }
        var set = this.data.sets
        this.setData({ sets: set.concat(res.result.user.data) })
        this.setData({ isLoading: false })
      })
    }
  },square() {
    var query = wx.createSelectorQuery().in(this);
    query.selectViewport().scrollOffset()
    query.select("#squareTo").boundingClientRect();
    query.exec(function (res) {
      var miss = res[0].scrollTop + res[1].top - 53;
      wx.pageScrollTo({
        scrollTop: miss
      });
    });
  }, search() {
    if(!this.data.searchText){
      wx.showToast({title: '请输入搜索内容',duration: 1000})
    }else{
      wx.navigateTo({url: 'search?word='+this.data.searchText})
    }
  },inputSearch(e){
    this.setData({searchText:e.detail.value})
  }
})